package com.xiaobai.demo;

import lombok.extern.slf4j.Slf4j;

/*
两阶段终止线程
 */

@Slf4j
public class TwoPhaseTermination2 {


    public static void main(String[] args) {
        TwoPhaseTerminationThread twoPhaseTerminationThread = new TwoPhaseTerminationThread();

        twoPhaseTerminationThread.start();
//        twoPhaseTerminationThread.start();
        try {
            Thread.sleep(3500);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }

        twoPhaseTerminationThread.stop();
    }
}

@Slf4j
class TwoPhaseTerminationThread {
    //监控线程
    private Thread monitorThread;
    //监控线程
    //这里有个缺点就是如果多次创建的话那么他的创建还是会是新的一个的 这样是存在问题的
    //打断标记
    volatile static boolean flag = false;
    //判断是否执行过start方法
    private boolean starting;

    public void start() {
        synchronized (this) {
            if (starting) {
                //犹豫模式
                log.info("监控线程已经启动");
            } else {
                starting = true;
            }
        }
        monitorThread = new Thread(() -> {
            while (true) {
                //不会清除打断标志
                if (flag) {
                    log.debug("Thread is interrupted");
                    break;
                }
                log.info("执行监控");
                try {
                    Thread.sleep(1000); //这个时候被打断的话就会进入到catch中，然后打断标志会重置为false
                } catch (InterruptedException e) {
                    flag = true;
                    log.error("线程被打断,{}", e.getMessage());
                }
            }
        });
        monitorThread.start();
    }

    public void stop() {
        flag = true;
        monitorThread.interrupt();
    }
}
